import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.POST  
import static groovyx.net.http.ContentType.JSON  
import static groovyx.net.http.ContentType.URLENC 
// 学校到期提醒，到期停止，在service里实现
class SchoolMgrController {
    def authenticateService 
    // 开启和关闭学校
    def goswitch = {
        if (params.id) {
            def school = School.get(params.id)
            school.enable = !school.enable
            school.save(flush: true)
        }
        redirect(action: "list" , controller: "school")
    }

    def init = {
        if (params.id) {
            def school = School.get(params.id)
            def name = '校长' + grailsApplication.config.grails.default.username.segment + school.id
            if (!Teacher.findBySchoolAndUsername(school, name)) { 
                def teacher = new Teacher(username: name , name: '校长', enabled : true ,sex : '男' , school : school)
                teacher.passwd = authenticateService.encodePassword(grailsApplication.config.grails.default.parent.passwd)
                teacher.save()
                Role.findByAuthority("ROLE_SCHOOL_MASTER").addToPeople(teacher)   
                flash.message = "初始化成功！"
            }else{
                flash.message = "不需要初始化！"
            }
        }
        redirect(action: "list" , controller: "school")
    }

    def initBlog = {
        if (params.id) {
            def school = School.get(params.id)
            // 调用blog程序，生成教师/学生的blog，blog对应的用户为此教师/学生   
            // START
            try {
                def http = new HTTPBuilder(grailsApplication.config.grails.default.blog.school.create.uri)
                def name = URLEncoder.encode("${school.name.toString()}",'UTF-8')

                def postBody = [name:"${name}",domain:"${school.domain}",subDomain:"${school.subDomain}",enable:"${school.enable}",area:"${school.area}",hostId:"${school.id}",start:"${school.start}",end:"${school.end}"]
                log.info("11111111") 
                http.post( path: '', body: postBody, 
                           requestContentType: URLENC) { resp, json -> 
                }
                return redirect(action: "list" , controller: "school")
            }catch (Exception ex ) {  
                if(ex.toString() == "groovyx.net.http.HttpResponseException: Not Found"){
                    flash.message = "创建Blog学校成功"
                }else{
                    flash.message = "${ex}"
                }
                
                return redirect(action: "list" , controller: "school")
            }
        }
        redirect(action: "list" , controller: "school")
    }

 }